import "./index.less"
import { Modal, Button, message, Upload, Input, Table, Space, TablePaginationConfig, Popconfirm, Form, InputNumber, } from 'antd';
import { SearchOutlined, CloudUploadOutlined,VerticalAlignBottomOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd/es/upload/interface';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useRef, useState } from 'react';
import {  getFileType } from '@/api/file';
import { useDispatch, useSelector } from "react-redux";
import { deleteFileAct, FileManner, uploadFileAct } from "@/redux/actions/fileMannger";
import { AxiosResponse } from "axios";
import { ReducersType } from "@/redux/store";
import { getAccountAct } from "@/redux/actions/account";
import compressAndDownload from "@/utils/FileZip";
import {  downURLFile } from "@/utils/fileDown";




let pageData = {
    page: 1,
    pageSize: 10,
    name: ''
}

interface fileType {
    id: number
    name: string,
    type: string,
    url: string,
    createTime: string,
    userId: number
}

interface type {
    id: number,
    name: string,
    saveStore: string,
    contentType: string,
    createTime: string
}

let typeData: type[] = [];


const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
};

export default function Form4() {

    const dispatch = useDispatch()
    //列表数据
    const data = useSelector((state: ReducersType) => {
        return state.fileMnaner
    })
    const userData = useSelector((state: ReducersType) => {
        return state.countReducer.accountData
    })

    const columns: ColumnsType<fileType> = [
        {
            title: '文件名',
            dataIndex: 'name',

        },
        {
            title: '类型',
            dataIndex: 'type',
        },
        {
            title: '地址',
            dataIndex: 'url',
        },
        {
            title: '创建人',
            dataIndex: 'userId',
            render: (_, record) => (
                <div key={record.id}>
                    {userData.map((item: type,index:number) => {
                        return (
                            <div key={index}>
                                {item.id == JSON.parse(sessionStorage.getItem("user") as string).id && item.name}
                            </div>
                        )
                    })}
                </div>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
        }, 
        {
            title: '操作',
            key: 'action',
            
            render: (_, record) => (
                <Space size="middle" key={record.id}>
                      <a className='edit' href="#" onClick={()=>downFile(record.url)} >下载</a>
                    <Popconfirm
                        title="提示"
                        description="该操作会永久删除改文件，是否继续？"
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => deleteFile(record.id)}
                        onCancel={deleteCancel}
                    >
                        <a className='delete' href="#" >删除</a>
                    </Popconfirm >
                </Space>

            )
        },
    ];
    const PageChange = (page: number, pageSize: number) => {
        pageData.page = page
        pageData.pageSize = pageSize
        setPageOption({ ...saveValue.current, pageSize, current: page })
        initData()
    }
    let pageConfig: TablePaginationConfig = {
        position: ['bottomRight'],
        defaultCurrent: 1,
        total: 0,
        showTotal: (total) => `共 ${total} 条`,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        onChange: PageChange,
        defaultPageSize: 10,
        pageSize: 10,
        current: 1
    }
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [selectedRows, setSelectedRows] = useState<fileType[]>([])
    /**
     * 
     * @param newSelectedRowKeys 选中的key
     * @param selectedRows 选中的文件数组对象
     */
    const onSelectChange = (newSelectedRowKeys: React.Key[], selectedRows: any) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        console.log("selectRowkeys Row", selectedRows);
        setSelectedRowKeys(newSelectedRowKeys)
        setSelectedRows(selectedRows)
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    //组件初始化
    //#region 
    let saveValue = useRef<TablePaginationConfig>()
    useEffect(() => {
        initPage()
        initData()
        initType()
        dispatch(getAccountAct())
    }, [])

    const [loading, setLoading] = useState(false);
    const [pageOption, setPageOption] = useState(pageConfig)


    useEffect(() => {
        //储存数据
        saveValue.current = pageOption
    }, [pageOption])

    const initData = () => {
        setLoading(true)
        dispatch(FileManner(pageData)).then((res: AxiosResponse<any, any> | string) => {
            if (res == "error") {
                message.error((res as unknown as AxiosResponse<any, any>).msg || "获取数据失败")
            } else {
                setPageOption({ ...saveValue.current, total: (res as AxiosResponse<any, any>).count })
                setLoading(false)
            }
        })
    }
    const initPage = () => {
        pageData = {
            page: 1,
            pageSize: 10,
            name: ''
        }
        setPageOption({ ...pageOption, pageSize: 10, current: 1 })
    }
    const initType = () => {
        getFileType().then((res) => {
            if (res.code == 1) {
                typeData = res.data
            } else {
                message.error(res.msg || "获取文件信息失败")
            }
        })
    }
    //#endregion

    //文件上传
    const props: UploadProps = {
        beforeUpload: (file) => {
            let fileType = typeData.find((item) => item.contentType == file.type)
            let formData = new FormData()
            formData.append('file', file)
            formData.append('type', (fileType as type).name)
            uploadFileAct(formData)
            return false;
        },
        showUploadList: false
    };

    //文件删除
    //#region 
    let deleteFile = (id: number) => {
        deleteFileAct(id).then((res: string) => {
            res == "success" && initData()
        })
    }
    const deleteCancel = () => {
        message.info("取消了删除操作")
    }
    //#endregion


    //#region 批量下载 
    const [form] = Form.useForm();
    const validateMessages = {
        required: "'${label}' 不能为空",
        // ...
    };
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const onFinish = () => {
        form.validateFields().then((values) => {
            setConfirmLoading(true)
            downFileZip(values.filename, values.level)
        })

    };
    const downFileZip = async (filename: string, level: number) => {
        compressAndDownload(selectedRows, filename, level).then(() => {
            setIsModalOpen(false);
            setConfirmLoading(false)
        })
    }
    //#endregion

    //#region 下载
    const downFile = (url:string)=>{
        downURLFile(url)
    }

   //#endregion
    return (
        <div className="Form4">
            <div className='header flex_a'>
                <Input size="middle" placeholder="请输入姓名" prefix={<SearchOutlined />} style={{ width: 250 }} allowClear />
                <Upload {...props} className={"upBtn"} >
                    <Button size="middle" type="primary" icon={<CloudUploadOutlined />}  >文件上传</Button>
                </Upload>
                <Button size="middle" type='primary' className={"deleteBtn"} onClick={showModal} icon={<VerticalAlignBottomOutlined />} >批量下载</Button>
            </div>
            <div className="table">
                <Table rowSelection={rowSelection} columns={columns} dataSource={data} pagination={pageOption} rowKey={item => item.id} loading={loading} />
            </div>
            <Modal title="批量下载" open={isModalOpen} onCancel={handleCancel} onOk={onFinish} destroyOnClose={true} confirmLoading={confirmLoading} afterClose={() => form.resetFields()} >
                <div className='Form'>
                    <Form {...layout} form={form} name="control-hooks" validateMessages={validateMessages} >
                        <Form.Item name="filename" label="文件名" rules={[{ required: true }]}>
                            <Input allowClear />
                        </Form.Item>
                        <Form.Item name="level" label="压缩级别" rules={[{ required: false, }]}>
                            <InputNumber type="number" min={1} max={9} defaultValue={9} />
                        </Form.Item>
                    </Form>
                </div>
            </Modal>
        </div>
    )
}